<template>
  <div class="container">
    <div class="content">
      <div class="login">

        <a-form @submit="perSubmit" :form="perform">
          <a-alert type="error" :closable="true" @close="onClose" v-if="errorShow" :message="errorMessage" showIcon
            style="margin-bottom: 24px;" />
          <a-form-item>
            <a-input onMouseOver="this.style.borderColor='#b3292c';" onMouseOut="this.style.borderColor='#d9d9d9';"
              v-decorator="[
                      'personName',
                      {rules: [{ required: true, message: '请输入手机号码', whitespace: true},{validator: validateCode}],validateTrigger: 'blur'}
                ]" size="large" placeholder="请输入手机号码">
              <a-icon slot="prefix" type="mobile" />
            </a-input>
          </a-form-item>
          <a-form-item>
            <a-input onMouseOver="this.style.borderColor='#b3292c';" onMouseOut="this.style.borderColor='#d9d9d9';"
              v-decorator="[
                      'perPassword',
                      {rules: [{ required: true, message: '请输入密码', whitespace: true}]}
                ]" size="large" placeholder="请输入密码" type="password">
              <a-icon slot="prefix" type="lock" />
            </a-input>
          </a-form-item>
          <div id="mpanel4" style="margin-top:28px;">
          </div>
          <div class="sm-style">
            <!-- <a-checkbox :checked="true">自动登录</a-checkbox> -->
            <a style="float: right;color:#b3292c;" @click="goPassword">忘记密码？</a>
          </div>
          <a-form-item>
            <a-button :loading="logging" style="width: 100%;" size="large" htmlType="submit" type="primary">登录
            </a-button>
          </a-form-item>
          <div class="loginBottom">
            <span>没有账号？</span>
            <router-link style="color:#b3292c;" to="/P">立即注册</router-link>
          </div>
        </a-form>

      </div>
    </div>
    <a-modal title="" v-model="visible" :footer="null" centered :width='400'>
      <p>审核拒绝： {{remark}}</p>
      <div style="display:flex;margin-top:30px;justify-content: center;">
        <a-button style="font-size: 13px;margin-right: 30px;" type="primary" @click='gostep4'>重新提交</a-button>
        <a-button style="font-size: 13px;margin-left: 20px;" type="primary" @click='hideModal'>取消</a-button>
      </div>
    </a-modal>
    <!-- <global-footer :link-list="linkList" :copyright="copyright"/> -->

  </div>
</template>


<script>
  import { message } from "ant-design-vue";
  import AForm from "ant-design-vue/es/form/Form";
  import ATabs from "ant-design-vue/es/tabs";
  import GlobalFooter from "../../layouts/GlobalFooter";
  import AFormItem from "ant-design-vue/es/form/FormItem";
  import AInput from "ant-design-vue/es/input/Input";
  import AIcon from "ant-design-vue/es/icon";
  import AInputGroup from "ant-design-vue/es/input/Group";
  import AButton from "ant-design-vue/es/button/button";
  import ACol from "ant-design-vue/es/grid/Col";
  import ARow from "ant-design-vue/es/grid/Row";
  import ACheckbox from "ant-design-vue/es/checkbox/Checkbox";
  import AAlert from "ant-design-vue/es/alert/index";
  import { JSEncrypt } from 'jsencrypt'
  import api from "@/common/api";

  const ATabPane = ATabs.TabPane;


  export default {
    name: "Login",
    components: {
      AAlert,
      ACheckbox,
      ACol,
      ARow,
      AButton,
      AInputGroup,
      AIcon,
      AInput,
      AFormItem,
      GlobalFooter,
      ATabPane,
      ATabs,
      AForm
    },
    data() {
      return {
        perform: this.$form.createForm(this),
        logging: false,
        size: "large",
        errorMessage: "",
        errorShow: false,
        perslide: Boolean,
        visible: false,
        remark: '',
      };
    },
    computed: {
      systemName() {
        return this.$store.state.setting.systemName;
      },
      linkList() {
        return this.$store.state.setting.footerLinks;
      },
      copyright() {
        return this.$store.state.setting.copyright;
      }
    },
    mounted() {


      /* eslint-disable */
      $('#mpanel4').slideVerify({
        type: 2,		//类型
        vOffset: 5,	//误差量，根据需求自行调整
        vSpace: 5,	//间隔
        imgName: ['image&quality=80&size=b9999_10000&sec=1558689827818&di=460971dcef166d21d211980847b0a344&imgtype=0&src=http%3A%2F%2Fwww.33lc.com%2Farticle%2FUploadPic%2F2012-7%2F201272714223895294.jpg'],
        imgSize: {
          width: '100%',
          height: '200px',
        },
        blockSize: {
          width: '40px',
          height: '38px',
        },
        barSize: {
          width: '100%',
          height: '38px',
        },
        ready: function () {
          window.perslide = false;
          window.verifyrefresh = this.verifyrefresh;
        },
        success: function () {
          window.perslide = true;

        },
        error: function () {
          window.perslide = false;
        },
        verifyrefresh: Function

      });
    },
    watch: {
      //  function tabchange(params) {

      //  }
    },
    methods: {
      showModal() {
        this.visible = true
      },
      hideModal() {
        this.visible = false
      },
      gostep4() {
        this.$router.push({
          path: "/PersonRegister/step4",
          query: { modify: true }
        });
      },
      goPassword() {
        this.$router.push("/org/changepassword");
      },
      validateCode(rule, value, callback) {
        // let reg = new RegExp('[\\u4E00-\\u9FFF]+', 'g')
        if (value && !/^1(3|4|5|6|7|8|9)\d{9}$/.test(value)) {
          /* eslint-disable-next-line */
          this.phone = false;
          callback("您输入的手机号格式有误！");
          return;
        } else {
          console.log(value);
          callback();
        }
      },
      perSubmit(e) {
        e.preventDefault();
        this.perform.validateFields((err, values) => {
          if (!err) {
            console.log(values)
            this.perslide = window.perslide;
            if (!this.perslide) {
              this.$message.warning('请滑动滑块进行验证！')
              return false;
            }
            this.logging = true;
            //获取会员公钥
            let username = this.perform.getFieldValue("personName");
            let params = { scope: 'login', key: username };
            api.fetchPubKey(params,
              res => {


                let pass = this.perform.getFieldValue("perPassword");
                pass = api.getEncryptData(res.data.pubKey, pass);
                this.login(username, pass);

                // encPassword = encodeURI(encPassword).replace(/\+/g, '%2B');


              });

          }
        });
      },
      login: function (username, password) {
        this.$axios
          .post("/agent/member/login", {
            username: username,
            password: password,
            key: username,
            memberType: "CU"
            // application: 'auth'
          })
          .then(res => {
            // console.log("res", res);
            let token = res.headers.authorization;
            localStorage.setItem("token", token);
            // console.log(
            //   "this.$axios.defaults.headers",
            //   this.$axios.defaults.headers
            // );
            this.$axios.defaults.headers.common["Authorization"] =
              res.headers.authorization;
            this.logging = false;
            const result = res.data;
            if (result.code === "OK") {
              this.remark = result.data.remark;
              sessionStorage.setItem('remark', this.remark)
              const memberNo = result.data.memberNo;
              sessionStorage.setItem("memberNo", memberNo);

              if (
                result.data.memberType == "CU" &&
                result.data.auditingStatusName == "待审核" &&
                result.data.canUpdate
              ) {

                this.$router.push("/userindex");

                // this.$message.info('审核中，暂不可登陆')
              } else if (
                result.data.memberType == "CU" &&
                result.data.auditingStatusName == "审核不通过"
              ) {
                this.$router.push("/userindex");
              } else if (
                result.data.auditingStatusName == "审核通过" &&
                result.data.memberType == "CU"
              ) {

                this.$router.push("/userindex");

              } else {
                this.$router.push("/PersonRegister/step4");
              }
              const user = result.data;

              // this.$message.success(result.message, 3);
            } else {
              this.errorMessage = result.message;
              console.log(this.errorMessage)
              if (this.errorMessage) {
                this.errorShow = true;
              } else {
                this.errorShow = false;
              }
              window.verifyrefresh()
              window.perslide = false;
            }
          });
      },
      handleChange(value) {
        console.log(value);
      },
      onClose() {
        this.errorShow = false;
      }
      // getEncryptData: function(pubKey,params){
      //   var crypt = new JSEncrypt();

      //   crypt.setKey(pubKey); //You can use also setPrivateKey and setPublicKey, they are both alias to setKey
      //   console.log("crypt:{}",crypt);
      //   //Eventhough the methods are called setPublicKey and setPrivateKey, remember
      //   //that they are only alias to setKey, so you can pass them both a private or
      //   //a public openssl key, just remember that setting a public key allows you to only encrypt.
      //    // Encrypt the data with the public key.
      //   var enc = crypt.encrypt(params);
      //   return enc;

      //  }
    }
  };
</script>

<style scoped>
  @import " ../../../static/css/color.css";

  .content {
    display: flex;
    justify-content: center;
  }

  .login {
    width: 400px;
    padding: 50px 40px 20px 40px;
    background: rgba(169, 169, 169, 0.5);
    border: 1px solid rgba(169, 169, 169, 0.5);
    border-radius: 10px;
  }

  .sm-style {
    height: 50px;
    line-height: 50px;
  }

  .loginBottom {
    height: 50px;
    line-height: 50px;
  }

  .tab-sty {
    width: 50%;
    text-align: center;
  }
</style>